package com.example.service.impl;

import com.example.mapper.CustomerMapper;
import com.example.pojo.Customer;
import com.example.service.ICustomerService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ICustomerServiceImpl implements ICustomerService {


    SqlSessionFactory sqlSessionFactory;
    SqlSession sqlSession;
    CustomerMapper customerMapper;
    {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();

        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 3. 创建SqlSessionFactory对象
        this.sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        sqlSession = this.sqlSessionFactory.openSession();

         customerMapper = sqlSession.getMapper(CustomerMapper.class);
    }


    @Override
    public List<Customer> finAll() {
        List<Customer> list = customerMapper.findAll();

        System.out.println(list);
        return list;

    }

    @Override
    public int saveCustomer(Customer customer) {
        int result=customerMapper.saveCustomer(customer);
        System.out.println(result);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public int deleteCustomerById(int id) {
        int result=customerMapper.deleteCustomerById(id);
        System.out.println(result);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public Customer findById(int id) {
        Customer customer=customerMapper.findById(id);
        System.out.println(customer);
        return customer;
    }

    @Override
    public int updateCustomerById(Customer customer) {
        int result=customerMapper.updateCustomerById(customer);
        System.out.println(result);
        sqlSession.commit();
        sqlSession.close();
        return result;
    }

    @Override
    public  List<Customer> findByLikeName(String name) {
        List<Customer> list=customerMapper.findByLikeName(name);
        System.out.println(list);
        return list;
    }
}
